<template>
  <div
    v-if="show"
    class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50"
    @click.self="$emit('close')"
  >
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white">
      <!-- 模态框标题 -->
      <div class="flex items-center justify-between mb-6">
        <h3 class="text-lg font-medium text-gray-900">
          {{ $t('pet.modal.title') }}
        </h3>
        <button
          @click="$emit('close')"
          class="text-gray-400 hover:text-gray-600"
        >
          <svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="mb-4 bg-red-50 border border-red-200 rounded-md p-4">
        <div class="flex">
          <ExclamationTriangleIcon class="h-5 w-5 text-red-400" />
          <div class="ml-3">
            <h3 class="text-sm font-medium text-red-800">{{ $t('pet.modal.operationFailed') }}</h3>
            <p class="mt-1 text-sm text-red-700">{{ error }}</p>
          </div>
        </div>
      </div>

      <!-- 宠物信息展示 -->
      <div class="space-y-6">
        <!-- 宠物照片 -->
        <div class="text-center">
          <div class="inline-block">
            <div class="w-32 h-32 rounded-lg overflow-hidden bg-gray-200 mx-auto">
              <img
                v-if="pet.photo_url"
                :src="getFullImageUrl(pet.photo_url)"
                :alt="pet.name"
                class="w-full h-full object-cover"
              />
              <div v-else class="w-full h-full flex items-center justify-center">
                <svg class="h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                </svg>
              </div>
            </div>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label class="block text-sm font-medium text-gray-700">{{ $t('post.fields.petName') }}</label>
            <p class="mt-1 text-sm text-gray-900">{{ pet.name || $t('pet.modal.unnamed') }}</p>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700">{{ $t('post.fields.petSpecies') }}</label>
            <p class="mt-1 text-sm text-gray-900">{{ getSpeciesLabel(pet.species) }}</p>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700">{{ $t('post.fields.petBreed') }}</label>
            <p class="mt-1 text-sm text-gray-900">{{ pet.breed || $t('pet.modal.unknown') }}</p>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700">{{ $t('post.fields.petColor') }}</label>
            <p class="mt-1 text-sm text-gray-900">{{ getColorLabel(pet.color) }}</p>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700">{{ $t('post.fields.petGender') }}</label>
            <p class="mt-1 text-sm text-gray-900">{{ getGenderLabel(pet.gender) }}</p>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700">{{ $t('post.fields.petAge') }}</label>
            <p class="mt-1 text-sm text-gray-900">{{ pet.age ? $t('pet.modal.ageYears', { age: pet.age }) : $t('pet.modal.unknown') }}</p>
          </div>
        </div>

        <!-- 描述 -->
        <div v-if="pet.description">
          <label class="block text-sm font-medium text-gray-700">{{ $t('post.fields.description') }}</label>
          <p class="mt-1 text-sm text-gray-900">{{ pet.description }}</p>
        </div>

        <!-- 创建时间 -->
        <div>
          <label class="block text-sm font-medium text-gray-700">{{ $t('pet.modal.addedAt') }}</label>
          <p class="mt-1 text-sm text-gray-900">{{ formatDate(pet.created_at) }}</p>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex justify-between pt-6 border-t mt-6">
        <button
          @click="handleDelete"
          class="btn-danger"
          :disabled="loading"
        >
          <span v-if="loading && loadingAction === 'delete'" class="inline-flex items-center">
            <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            {{ $t('pet.modal.deleting') }}
          </span>
          <span v-else>{{ $t('pet.modal.deletePet') }}</span>
        </button>

        <div class="flex space-x-3">
          <button
            @click="$emit('close')"
            class="btn-secondary"
            :disabled="loading"
          >
            {{ $t('common.close') }}
          </button>
          <button
            @click="showEditForm = true"
            class="btn-primary"
            :disabled="loading"
          >
            {{ $t('pet.modal.editInfo') }}
          </button>
        </div>
      </div>
    </div>

    <!-- 编辑表单模态框 -->
    <PetForm
      v-if="showEditForm"
      :show="showEditForm"
      :pet="pet"
      @close="showEditForm = false"
      @success="handleEditSuccess"
    />

    <!-- 删除确认模态框 -->
    <div
      v-if="showDeleteConfirm"
      class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-60"
      @click.self="showDeleteConfirm = false"
    >
      <div class="relative top-1/2 transform -translate-y-1/2 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="text-center">
          <ExclamationTriangleIcon class="mx-auto h-12 w-12 text-red-500 mb-4" />
          <h3 class="text-lg font-medium text-gray-900 mb-2">{{ $t('pet.modal.confirmDelete') }}</h3>
          <p class="text-sm text-gray-600 mb-6">
            {{ $t('pet.modal.confirmDeleteMessage', { name: pet.name }) }}
          </p>
          <div class="flex justify-center space-x-3">
            <button
              @click="showDeleteConfirm = false"
              class="btn-secondary"
              :disabled="loading"
            >
              {{ $t('common.cancel') }}
            </button>
            <button
              @click="confirmDelete"
              class="btn-danger"
              :disabled="loading"
            >
              <span v-if="loading && loadingAction === 'delete'" class="inline-flex items-center">
                <svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                {{ $t('pet.modal.deleting') }}
              </span>
              <span v-else>{{ $t('pet.modal.confirmDeleteAction') }}</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { ExclamationTriangleIcon } from '@heroicons/vue/24/outline'
import { petService } from '@/services/pets'
import { getFullImageUrl, formatDate } from '@/utils/helpers'
import { usePetSpeciesOptions, usePetColorOptions, usePetGenderOptions } from '@/utils/i18n-options'
import PetForm from '@/components/PetForm.vue'
import type { Pet } from '@/types'

// Props
interface Props {
  show: boolean
  pet: Pet
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  close: []
  updated: [pet: Pet]
  deleted: [petId: number]
}>()

const { t } = useI18n()

// 状态
const loading = ref(false)
const loadingAction = ref('')
const error = ref('')
const showEditForm = ref(false)
const showDeleteConfirm = ref(false)

// 国际化选项
const petSpeciesOptions = computed(() => usePetSpeciesOptions())
const petColorOptions = computed(() => usePetColorOptions())
const petGenderOptions = computed(() => usePetGenderOptions())

// 获取标签方法
const getSpeciesLabel = (species: string) => {
  const speciesOption = petSpeciesOptions.value.find((s: any) => s.value === species)
  return speciesOption?.label || species
}

const getColorLabel = (color: string) => {
  const colorOption = petColorOptions.value.find((c: any) => c.value === color)
  return colorOption?.label || color
}

const getGenderLabel = (gender: string) => {
  const genderOption = petGenderOptions.value.find((g: any) => g.value === gender)
  return genderOption?.label || t('pet.modal.unknown')
}

// 处理编辑成功
const handleEditSuccess = (updatedPet: Pet) => {
  showEditForm.value = false
  emit('updated', updatedPet)
}

// 处理删除
const handleDelete = () => {
  showDeleteConfirm.value = true
}

// 确认删除
const confirmDelete = async () => {
  try {
    loading.value = true
    loadingAction.value = 'delete'
    error.value = ''

    const response = await petService.delete(props.pet.id)

    if (response.success) {
      showDeleteConfirm.value = false
      emit('deleted', props.pet.id)
    } else {
      throw new Error(response.message || t('pet.modal.deleteFailed'))
    }
  } catch (err) {
    console.error('删除宠物失败:', err)
    error.value = err instanceof Error ? err.message : t('pet.modal.deleteFailedRetry')
  } finally {
    loading.value = false
    loadingAction.value = ''
  }
}
</script>

<style scoped>
.btn-danger {
  @apply bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md text-sm font-medium transition-colors;
}

.btn-danger:disabled {
  @apply bg-red-400 cursor-not-allowed;
}
</style>
